﻿using System.Threading;
using Skynet.CommonLibrary.ThreadQueue.Interface;

namespace Skynet.CommonLibrary.ThreadQueue.Center
{
    /// <summary>
    /// 装饰中心
    /// </summary>
    ///<remarks>
    /// 作者：         李志强
    /// 开发时间：  2011-04-18
    /// </remarks>
    public abstract class DceoratorCenter : IExecutionCenter, IComponent
    {
        private readonly Thread _processThread;
        //是否等待标识
        private bool _isWait;
        //信号量
        protected AutoResetEvent AutoProccessEvent = new AutoResetEvent(false);

        protected DceoratorCenter()
        {
            _processThread = new Thread(new ParameterizedThreadStart(o => DataProcess())) {IsBackground = true};
        }

        /// <summary>
        /// 开始处理
        /// </summary>
        public virtual void StartExecution()
        {
            _processThread.Start();
        }

        /// <summary>
        /// 继续处理
        /// </summary>
        public virtual void ContinueExecution()
        {
            IsWait = false;
        }

        /// <summary>
        /// 线程是否在等待
        /// </summary>
        public bool IsWait
        {
            get { return _isWait; }
            set 
            {
                if (_isWait == value)
                    return;
                _isWait = value;
                if (value == false )
                {
                    AutoProccessEvent.Set();
                }
                else
                { 
                    AutoProccessEvent.WaitOne(); 
                }

            }
        }

        /// <summary>
        /// 数据操作处理
        /// </summary>
        protected internal abstract void DataProcess();

        #region IComponent 成员
        IComponent _component;

        /// <summary>
        /// 组合一个新组件
        /// </summary>
        /// <param name="component">组件</param>
        public void SetComponent(IComponent component)
        {
            _component = component;
        }

        protected object OperationData { get; set; }
        public virtual void Operation(object o) 
        {
            if (_component == null)
                return;

            _component.Operation(o);
        }

        #endregion
    }

}
